package com.showsu.editor.controller.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.showsu.editor.controller.BaseController;
import com.showsu.editor.entity.bigmodel.ChatCompletionsResponse;
import com.showsu.editor.entity.dto.XhsEditorAwemeDTO;
import com.showsu.editor.entity.po.*;
import com.showsu.editor.entity.vo.response.EditorTemplateTabsVO;
import com.showsu.editor.entity.vo.response.EditorTemplateTitleVO;
import com.showsu.editor.enums.ResultCode;
import com.showsu.editor.enums.RowFlagEnum;
import com.showsu.editor.entity.dto.XhsEditorDeleteMeidiaImgDTO;
import com.showsu.editor.entity.po.TblXhsEditorAwemeRecord;
import com.showsu.editor.entity.po.TblXhsEditorMediaRecord;
import com.showsu.editor.entity.vo.response.XhsEditorAwemeVO;
import com.showsu.editor.enums.*;
import com.showsu.editor.manage.XhsBusinessManager;
import com.showsu.editor.manage.XhsEditorAwemeBusinessManager;
import com.showsu.editor.service.*;
import com.showsu.editor.utils.*;
import com.showsu.editor.utils.aliyun.OssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: jph
 * @Description:
 * @Date: Created in 10:31 下午 2024/9/19
 * @Modified By:
 */
@RestController
@Slf4j
@Api(value = "XhsEditorBusinessController", tags = "xhs编辑器业务")
@RequestMapping("/api/xhs/editor")
public class XhsEditorAwemeBusinessController extends BaseController {

    @Autowired
    private OssUtil ossUtil;

    @Autowired
    private RedisUtil redisUtil;


    @Autowired
    private IXhsEditorAwemeRecordService editorAwemeRecordService;

    @Autowired
    private IXhsEditorMediaRecordService mediaRecordService;

    @Autowired
    private XhsEditorAwemeBusinessManager editorAwemeBusinessManager;

    @Autowired
    private IAIChatCompletionsService aiChatCompletionsService;

    @Autowired
    private XhsBusinessManager xhsBusinessManager;

    @Autowired
    private XhsEditorAwemeBusinessManager xhsEditorAwemeBusinessManager;

    @Autowired
    private IXhsEditorTemplateTagsService editorTemplateTagsService;

    @Autowired
    private IXhsEditorTemplateTitleService editorTemplateTitleService;

    /**
     * 检查用户是否拥有使用保存笔记业务的权限
     * @param user
     * @return
     */
    public boolean checkSaveAwemeLimit(TblUser user) {
        return true;
    }

    /**
     * 检查用户是否拥有使用上传笔记图片业务的权限
     * @param user
     * @return
     */
    public boolean checkUploadImgLimit(TblUser user) {
        return true;
    }


    /**
     * xhs编辑器 保存笔记
     * @return
     */
    @PostMapping("/aweme")
    @ApiOperation(value = "xhs编辑器 保存笔记", notes = "xhs编辑器 保存笔记")
    @ResponseBody
    public BsResult saveAweme(@RequestBody XhsEditorAwemeDTO awemeDTO) {
        if(awemeDTO==null){
            return BsResult.error(ResultCode.PARAM_MISS);
        }
        TblUser user = getUser();
        if (user == null || 0L == user.getId()) {
            return BsResult.error(ResultCode.UN_LOGINED);
        }
        VipLevelEnum vipLevelEnum = VipLevelEnum.getByLevel(user.getVipLevelCode());
        if (vipLevelEnum==null||!vipLevelEnum.getNoteEditor()) {
            return BsResult.error(ResultCode.REQ_REJECT);
        }
        TblXhsEditorAwemeRecord result=null;
        //需要增加新增笔记的权限控制，编辑笔记目前不做权限控制
        if(StringUtils.isNotBlank(awemeDTO.getId())){
            result=editorAwemeRecordService.getById(awemeDTO.getId());
            if(result==null){
                return BsResult.error(ResultCode.RESOURCE_NOT_VALID);
            }
            if(RowFlagEnum.Deleted.getCode()==result.getFlag()) {
                return BsResult.error(ResultCode.RESOURCE_NOT_FOUND);
            }
            if(ModerationStatusEnum.Disable.getCode()==result.getStatus()){
                return BsResult.error(ResultCode.REQ_REJECT.getCode(),"笔记已被封禁");
            }

            if (!result.getUserId().equals(user.getId())) {
                return BsResult.error(ResultCode.REQ_REJECT);
            }
        }else{
            result=new TblXhsEditorAwemeRecord();
            awemeDTO.setId(null);
            VipLevelEnum userVipLevel=VipLevelEnum.getByLevel(user.getVipLevelCode());
            //会员已经过期
            if (!VipLevelEnum.FREE.equals(userVipLevel)
                    &&user.getVipEndTime().compareTo(new Date()) < 0) {
                userVipLevel=VipLevelEnum.FREE;
            }
            //新增笔记的权限控制
            Date now =DateUtil.date();
            int toDayCount=editorAwemeRecordService.queryCountOfUserWithDate(user.getId(),DateUtil.beginOfDay(now),DateUtil.endOfDay(now));
            if(VipLevelEnum.FREE.equals(userVipLevel)){
                if(toDayCount>=userVipLevel.getNoteNum()){
                    return BsResult.error(ResultCode.FREE_LIMITED.getCode(),"今日笔记存储数量已不足（"+userVipLevel.getNoteNum()+"篇/天），请删除部分笔记或开通会员");
                }
                int count=editorAwemeRecordService.queryCountOfUser(user.getId());
                if(count>=Constant.editorAwemeFreeMaxCount){
                    return BsResult.error(ResultCode.FREE_LIMITED.getCode(),"笔记存储数量已不足（共"+Constant.editorAwemeFreeMaxCount+"篇），请删除部分笔记或开通会员");
                }
            }else{
                if(toDayCount>=userVipLevel.getNoteNum()){
                    return BsResult.error(ResultCode.COUNT_LIMITED.getCode(),"今日笔记存储数量已不足（"+userVipLevel.getNoteNum()+"篇/天），请删除部分笔记或升级会员");
                }
            }
        }
        //笔记图片数量限制
        if(StringUtils.isNotBlank(awemeDTO.getImageUrl())){
            try {
                List<String> imgList=JSON.parseArray(awemeDTO.getImageUrl(),String.class);
                if(imgList!=null&&imgList.size()>=Constant.editorImgMaxCount){
                    return BsResult.error(ResultCode.PIC_COUNT_LIMIT);
                }
            }catch (Exception ignored){}
        }

        String iText="";
        if(StringUtils.isNotBlank(awemeDTO.getTitle())){
            try {
                iText+=AESUtil.decrypt(awemeDTO.getTitle());
            }catch (Exception e){
                return BsResult.error(ResultCode.RESOURCE_NOT_VALID);
            }
            if(StringUtil.realStringLength(iText)>100){
                return BsResult.error(ResultCode.PARAM_VALID_ERROR.getCode(),"标题超过字数");
            }
        }
        if(StringUtils.isNotBlank(awemeDTO.getContent())){
            String content=null;
            try {
                content=AESUtil.decrypt((awemeDTO.getContent()));
            }catch (Exception e){
                return BsResult.error(ResultCode.RESOURCE_NOT_VALID);
            }
            if(StringUtil.realStringLength(content.replace("\n", ""))>2000){
                return BsResult.error(ResultCode.PARAM_VALID_ERROR.getCode(),"正文超过字数");
            }
            iText+=content;
        }
        String resultText=result.getTitle()+result.getContent();
        EditorAwemeStatusEnum awemeStatusEnum=EditorAwemeStatusEnum.getByCode(result.getStatus());
        if(StringUtils.isNotBlank(iText)
                &&!resultText.equals(awemeDTO.getTitle()+awemeDTO.getContent())){
            ModerationRiskLevelEnum riskLevelEnum=editorAwemeBusinessManager.wxTextModeration(iText);
            if(riskLevelEnum.getLevel()>=ModerationRiskLevelEnum.high.getLevel()){
                return BsResult.error(ResultCode.PARAM_VALID_NON_COMPLIANT);
            }
            awemeStatusEnum=EditorAwemeStatusEnum.TextReview;
        }
        if(EditorAwemeStatusEnum.TextReview!=awemeStatusEnum){
            awemeStatusEnum=EditorAwemeStatusEnum.Review;
        }
        BeanUtil.copyProperties(awemeDTO,result,CopyOptions.create(TblXhsEditorAwemeRecord.class,true));
        result.setStatus(awemeStatusEnum.getCode());
        result.setLastUpdate(null);
        editorAwemeRecordService.saveOrUpdateRecord(getClientRequest(),user.getId(),result);
        return BsResult.success(result.getId());
    }
    /**
     * xhs编辑器 删除笔记
     * @param eAwemeId
     * @return
     */
    @PostMapping("/deleteAweme/{eAwemeId}")
    @ApiOperation(value = "xhs编辑器 删除笔记", notes = "xhs编辑器 删除笔记")
    @ResponseBody
    public BsResult deleteAweme(@PathVariable("eAwemeId") String eAwemeId) {
        if(StringUtils.isBlank(eAwemeId)){
            return BsResult.error(ResultCode.RESOURCE_NOT_VALID);
        }
        Long userId = getUserId();
        if (userId == null || 0L == userId) {
            return BsResult.error(ResultCode.UN_LOGINED);
        }
        TblXhsEditorAwemeRecord awemeRecord=editorAwemeRecordService.getById(eAwemeId);
        if(awemeRecord==null||RowFlagEnum.Deleted.getCode()==awemeRecord.getFlag()) {
            return BsResult.error(ResultCode.RESOURCE_NOT_FOUND);
        }
        if (!awemeRecord.getUserId().equals(userId)) {
            return BsResult.error(ResultCode.REQ_REJECT);
        }
        if(StringUtils.isNotBlank(awemeRecord.getImageUrl())){
            List<String> imgList=null;
            try {
                imgList=JSON.parseArray(awemeRecord.getImageUrl(),String.class);
            }catch (Exception ignored){}
            if(!CollectionUtils.isEmpty(imgList)){
                for(String imgUrl : imgList){
                    List<TblXhsEditorMediaRecord> mediaRecordList= mediaRecordService.list(new QueryWrapper<TblXhsEditorMediaRecord>().lambda()
                            .eq(TblXhsEditorMediaRecord::getUserId, userId)
                            .eq(TblXhsEditorMediaRecord::getMediaUrl, imgUrl)
                            .eq(TblXhsEditorMediaRecord::getFlag, RowFlagEnum.UnDelete.getCode()));
                    //没有找到该用户要删除的图片链接
                    if(CollectionUtils.isEmpty(mediaRecordList)){
                        continue;
                    }
                    boolean isOk=ossUtil.deleteXhsEditorDirFile(imgUrl);
                    mediaRecordService.remove(new QueryWrapper<TblXhsEditorMediaRecord>().lambda()
                            .eq(TblXhsEditorMediaRecord::getUserId, userId)
                            .eq(TblXhsEditorMediaRecord::getMediaUrl, imgUrl)
                            .eq(TblXhsEditorMediaRecord::getFlag, RowFlagEnum.UnDelete.getCode()));
                }
            }
        }
        editorAwemeRecordService.removeById(awemeRecord.getId());
        return BsResult.success("");
    }

    /**
     * xhs编辑器 上传图片素材
     * @param imgFile
     * @return
     */
    @PostMapping("/uploadMediaImg")
    @ApiOperation(value = "xhs编辑器 上传图片素材", notes = "xhs编辑器 上传图片素材")
    @ResponseBody
    public BsResult uploadMediaImg(
            @RequestParam(value = "imgFile", required = true) MultipartFile imgFile,
            @RequestParam(value = "eAwemeId", required = true) String eAwemeId,
            @RequestParam(value = "digest", required = false) String digest) {
        if (imgFile == null||StringUtils.isBlank(eAwemeId)) {
            return BsResult.error(ResultCode.PARAM_MISS);
        }
        TblUser user = getUser();
        if (user == null || 0L == user.getId()) {
            return BsResult.error(ResultCode.UN_LOGINED);
        }
        VipLevelEnum userVipLevel=VipLevelEnum.getByLevel(user.getVipLevelCode());
        if(userVipLevel==null||!userVipLevel.getNotePhotoUpload()){
            return BsResult.error(ResultCode.FREE_LIMITED.getCode(),"请升级会员");
        }
        TblXhsEditorAwemeRecord awemeRecord=editorAwemeRecordService.getById(eAwemeId);
        if(awemeRecord==null||RowFlagEnum.Deleted.getCode()==awemeRecord.getFlag()) {
            return BsResult.error(ResultCode.RESOURCE_NOT_FOUND);
        }
        if (!awemeRecord.getUserId().equals(user.getId())) {
            return BsResult.error(ResultCode.REQ_REJECT);
        }
        if(ModerationStatusEnum.Disable.getCode()==awemeRecord.getStatus()){
            return BsResult.error(ResultCode.REQ_REJECT.getCode(),"笔记已被封禁");
        }
        List<String> imgList=null;
        if(StringUtils.isNotBlank(awemeRecord.getImageUrl())){
            try {
                imgList=JSON.parseArray(awemeRecord.getImageUrl(),String.class);
            }catch (Exception ignored){}
        }
        if(imgList==null){
            imgList=new ArrayList<>();
        }
        //笔记图片数量限制
        if(imgList.size()>=Constant.editorImgMaxCount){
            return BsResult.error(ResultCode.PIC_COUNT_LIMIT);
        }
        //图片大小限制：20M
        if (imgFile.getSize() >Constant.editorImgMaxSize) {
            return BsResult.error(ResultCode.PIC_SIZE_LIMIT);
        }
        // 获取文件名
        String fileName = imgFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        if(!StringUtils.endsWithIgnoreCase(prefix,".png")
                &&!StringUtils.endsWithIgnoreCase(prefix,".jpg")
                &&!StringUtils.endsWithIgnoreCase(prefix,".jpeg")
                &&!StringUtils.endsWithIgnoreCase(prefix,".webp")
                &&!StringUtils.endsWithIgnoreCase(prefix,".gif")
        ){
            return BsResult.error(ResultCode.PIC_TYPE_ERROR);
        }
        //把图片上传到oss
        String fileOssUrl = null;
        try (InputStream inputStream =imgFile.getInputStream()){
            fileOssUrl = ossUtil.uploadXhsEditorDirFile2AliyunOss(inputStream, Constant.hsxPc + UUID.randomUUID().toString().replaceAll("-","") +prefix);
        } catch (IOException e) {}
        if (StringUtils.isBlank(fileOssUrl)) {
            return BsResult.error(ResultCode.PIC_UPLOAD_FAIL);
        }
        try {
            ModerationRiskLevelEnum riskLevelEnum=editorAwemeBusinessManager.imageModeration(fileOssUrl);
            ModerationStatusEnum mediaStatusEnum= ModerationStatusEnum.Enable;
            switch (riskLevelEnum){
                case high:
                    ossUtil.deleteXhsEditorDirFile(fileOssUrl);
                    mediaRecordService.saveRecord(getClientRequest(), user.getId(),1, fileOssUrl,"检测图片不合规"+digest, ModerationStatusEnum.Disable.getCode());
                    return BsResult.error(ResultCode.PARAM_VALID_NON_COMPLIANT.getCode(),"含有严重不合规图片，请更换图片");
                case medium:
                    mediaStatusEnum= ModerationStatusEnum.ManualReview;
                    break;
                case unknown:
                    mediaStatusEnum= ModerationStatusEnum.ManualReview;
            }
            mediaRecordService.saveRecord(getClientRequest(), user.getId(),1, fileOssUrl,null,mediaStatusEnum.getCode());
            imgList.add(fileOssUrl);
            awemeRecord.setImageUrl(JSON.toJSONString(imgList));
            EditorAwemeStatusEnum awemeStatusEnum=EditorAwemeStatusEnum.getByCode(awemeRecord.getStatus());
            if(EditorAwemeStatusEnum.TextReview!=awemeStatusEnum){
                awemeStatusEnum=EditorAwemeStatusEnum.Review;
            }
            awemeRecord.setStatus(awemeStatusEnum.getCode());
            awemeRecord.setLastUpdate(null);
            editorAwemeRecordService.saveOrUpdateRecord(getClientRequest(),user.getId(),awemeRecord);
            return BsResult.success(fileOssUrl);
        } catch (Exception ex) {
            log.error("xhs编辑器 上传图片素材-异常:{}", ex);
            if(StringUtils.isNotBlank(fileOssUrl)){
                ossUtil.deleteXhsEditorDirFile(fileOssUrl);
            }
            return BsResult.error(ResultCode.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * xhs编辑器 删除图片素材
     * @param dto
     * @param dto
     * @return
     */
    @PostMapping("/deleteMediaImg")
    @ApiOperation(value = "xhs编辑器 上传图片素材", notes = "xhs编辑器 上传图片素材")
    @ResponseBody
    public BsResult deleteMediaImg(@RequestBody XhsEditorDeleteMeidiaImgDTO dto) {
        if (dto==null||StringUtils.isBlank(dto.getImgUrl())) {
            return BsResult.error(ResultCode.PARAM_MISS);
        }
        Long userId = getUserId();
        if (userId == null || 0L == userId) {
            return BsResult.error(ResultCode.UN_LOGINED);
        }
        List<TblXhsEditorMediaRecord> mediaRecordList= mediaRecordService.list(new QueryWrapper<TblXhsEditorMediaRecord>().lambda()
                .eq(TblXhsEditorMediaRecord::getUserId, userId)
                .eq(TblXhsEditorMediaRecord::getMediaUrl, dto.getImgUrl())
                .eq(TblXhsEditorMediaRecord::getFlag, RowFlagEnum.UnDelete.getCode()));
        //没有找到该用户要删除的图片链接
        if(CollectionUtils.isEmpty(mediaRecordList)){
            return BsResult.error(ResultCode.PARAM_VALID_ERROR);
        }
        try {
            boolean isOk=ossUtil.deleteXhsEditorDirFile(dto.getImgUrl());
            mediaRecordService.remove(new QueryWrapper<TblXhsEditorMediaRecord>().lambda()
                    .eq(TblXhsEditorMediaRecord::getUserId, userId)
                    .eq(TblXhsEditorMediaRecord::getMediaUrl, dto.getImgUrl())
                    .eq(TblXhsEditorMediaRecord::getFlag, RowFlagEnum.UnDelete.getCode()));
            return BsResult.success("");
        } catch (Exception ex) {
            log.error("xhs编辑器 删除图片素材-异常:{}", ex);
            return BsResult.error(ResultCode.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/aweme/list")
    @ApiOperation(value = "xhs编辑器-获取用户笔记列表-getUserAwemeList", notes = "xhs编辑器-获取用户笔记列表-getUserAwemeList")
    @ResponseBody
    public BsResult getUserAwemeList(@RequestParam(required = false) Integer state,@RequestParam(required = false) Integer type){
        Long userId = getUserId();
        if (userId == null || 0L == userId) {
            return BsResult.error(ResultCode.UN_LOGINED);
        }
        List<TblXhsEditorAwemeRecord> awemeRecordList=editorAwemeRecordService.queryByUserId(userId);
        if(awemeRecordList==null){return BsResult.error(ResultCode.RESOURCE_NOT_FOUND);}
        List<XhsEditorAwemeVO> respList=new ArrayList<>();
        for(TblXhsEditorAwemeRecord awemeRecord : awemeRecordList){
            XhsEditorAwemeVO resp = BeanUtil.toBean(awemeRecord, XhsEditorAwemeVO.class);
            if(ModerationStatusEnum.Disable.getCode()==awemeRecord.getStatus()){
                resp.setTitle(null);
                resp.setContent(null);
                resp.setImageUrl(null);
            }
            respList.add(resp);
        }
        return BsResult.success(respList);
    }

    @GetMapping("/aweme/{eAwemeId}")
    @ApiOperation(value = "xhs编辑器-获取用户笔记详情-getUserAwemeDetail", notes = "xhs编辑器-获取用户笔记详情-getUserAwemeDetail")
    @ResponseBody
    public BsResult getUserAwemeDetail(@PathVariable("eAwemeId") String eAwemeId) {
        if(StringUtils.isBlank(eAwemeId)){
            return BsResult.error(ResultCode.RESOURCE_NOT_VALID);
        }
        Long userId = getUserId();
        if (userId == null || 0L == userId) {
            return BsResult.error(ResultCode.UN_LOGINED);
        }
        TblXhsEditorAwemeRecord awemeRecord = editorAwemeRecordService.getById(eAwemeId);
        if (awemeRecord != null && RowFlagEnum.UnDelete.getCode() == awemeRecord.getFlag()) {
            if (!awemeRecord.getUserId().equals(userId)) {
                return BsResult.error(ResultCode.REQ_REJECT);
            }
            if(ModerationStatusEnum.Disable.getCode()==awemeRecord.getStatus()){
                return BsResult.error(ResultCode.REQ_REJECT.getCode(),"笔记已被封禁");
            }
            XhsEditorAwemeVO resp = BeanUtil.toBean(awemeRecord, XhsEditorAwemeVO.class);
            return BsResult.success(resp);
        }
        return BsResult.error(ResultCode.RESOURCE_NOT_FOUND);
    }

    @PostMapping("/aweme/preview/{eAwemeId}")
    @ApiOperation(value = "xhs编辑器-获取用户笔记详情-getUserAwemeDetail", notes = "xhs编辑器-获取用户笔记详情-getUserAwemeDetail")
    @ResponseBody
    public BsResult postUserAwemePreview(@PathVariable("eAwemeId") String eAwemeId,@RequestBody XhsEditorAwemeDTO awemeDTO) {
        if(StringUtils.isBlank(eAwemeId)){
            return BsResult.error(ResultCode.RESOURCE_NOT_VALID);
        }
        Long userId = getUserId();
        if (userId == null || 0L == userId) {
            return BsResult.error(ResultCode.UN_LOGINED);
        }
        TblXhsEditorAwemeRecord awemeRecord = editorAwemeRecordService.getById(eAwemeId);
        if (awemeRecord != null && RowFlagEnum.UnDelete.getCode() == awemeRecord.getFlag()) {
            if (!awemeRecord.getUserId().equals(userId)) {
                return BsResult.error(ResultCode.REQ_REJECT);
            }
            if(ModerationStatusEnum.Disable.getCode()==awemeRecord.getStatus()){
                return BsResult.error(ResultCode.REQ_REJECT.getCode(),"笔记已被封禁");
            }
            if(redisUtil.keyExists(Constant.REDIS_KEY_CREATOR_DATASHOWS_AWEME_PREVIEW+eAwemeId)){
                String previewId=redisUtil.getValue(Constant.REDIS_KEY_CREATOR_DATASHOWS_AWEME_PREVIEW+eAwemeId);
                redisUtil.deleteKey(Constant.REDIS_KEY_CREATOR_DATASHOWS_AWEME_PREVIEW+previewId);
            }

            String previewId= RandomUtil.randomString(Constant.CREATOR_DATASHOWS_AWEME_PREVIEW_BASE_CHAR_NUMBER,12);
            redisUtil.setValueWithExpire(Constant.REDIS_KEY_CREATOR_DATASHOWS_AWEME_PREVIEW+previewId,eAwemeId,10, TimeUnit.MINUTES);
            redisUtil.setValueWithExpire(Constant.REDIS_KEY_CREATOR_DATASHOWS_AWEME_PREVIEW+eAwemeId,previewId,10, TimeUnit.MINUTES);
            if(StringUtils.isNotBlank(awemeDTO.getContent())){
                redisUtil.setValueWithExpire(Constant.REDIS_KEY_CREATOR_DATASHOWS_AWEME_PREVIEW_CONTENT+previewId,awemeDTO.getContent(),10, TimeUnit.MINUTES);
            }
            return BsResult.success(xhsEditorAwemeBusinessManager.getAwemePreviewUrl()+previewId);
        }
        return BsResult.error(ResultCode.RESOURCE_NOT_FOUND);
    }

    @GetMapping("/aweme/preview/{previewId}")
    @ApiOperation(value = "xhs编辑器-获取用户笔记详情-getUserAwemeDetail", notes = "xhs编辑器-获取用户笔记详情-getUserAwemeDetail")
    @ResponseBody
    public BsResult getUserAwemePreview(@PathVariable("previewId") String previewId) {
        if(StringUtils.isBlank(previewId)){
            return BsResult.error(ResultCode.RESOURCE_NOT_VALID);
        }
        if(!redisUtil.keyExists(Constant.REDIS_KEY_CREATOR_DATASHOWS_AWEME_PREVIEW+previewId)){
            return BsResult.error(ResultCode.RESOURCE_NOT_VALID);
        }
        String eAwemeId=redisUtil.getValue(Constant.REDIS_KEY_CREATOR_DATASHOWS_AWEME_PREVIEW+previewId);
        TblXhsEditorAwemeRecord awemeRecord = editorAwemeRecordService.getById(eAwemeId);
        if (awemeRecord != null && RowFlagEnum.UnDelete.getCode() == awemeRecord.getFlag()) {
            if(ModerationStatusEnum.Disable.getCode()==awemeRecord.getStatus()){
                return BsResult.error(ResultCode.REQ_REJECT.getCode(),"笔记已被封禁");
            }
            XhsEditorAwemeVO resp = BeanUtil.toBean(awemeRecord, XhsEditorAwemeVO.class);
            if(redisUtil.keyExists(Constant.REDIS_KEY_CREATOR_DATASHOWS_AWEME_PREVIEW_CONTENT+previewId)){
                try {
                    String content=redisUtil.getValue(Constant.REDIS_KEY_CREATOR_DATASHOWS_AWEME_PREVIEW_CONTENT+previewId);
                    resp.setContentHtml(content);
                }catch (Exception e){
                }
            }
            return BsResult.success(resp);
        }
        return BsResult.error(ResultCode.RESOURCE_NOT_FOUND);
    }

    @GetMapping("/aweme/shareConfig/{previewId}")
    @ApiOperation(value = "xhs编辑器-获取用户笔记详情-getUserAwemeDetail", notes = "xhs编辑器-获取用户笔记详情-getUserAwemeDetail")
    @ResponseBody
    public BsResult getUserAwemeShareConfig(@PathVariable("previewId") String previewId) {
        if(StringUtils.isBlank(previewId)){
            return BsResult.error(ResultCode.RESOURCE_NOT_VALID);
        }
        if(!redisUtil.keyExists(Constant.REDIS_KEY_CREATOR_DATASHOWS_AWEME_PREVIEW+previewId)){
            return BsResult.error(ResultCode.RESOURCE_NOT_VALID);
        }
        String eAwemeId=redisUtil.getValue(Constant.REDIS_KEY_CREATOR_DATASHOWS_AWEME_PREVIEW+previewId);
        TblXhsEditorAwemeRecord awemeRecord = editorAwemeRecordService.getById(eAwemeId);
        if (awemeRecord != null && RowFlagEnum.UnDelete.getCode() == awemeRecord.getFlag()) {
            if(ModerationStatusEnum.Disable.getCode()==awemeRecord.getStatus()){
                return BsResult.error(ResultCode.REQ_REJECT.getCode(),"笔记已被封禁");
            }
            String result=xhsEditorAwemeBusinessManager.xhsAgoraSignature();
            if(StringUtils.isBlank(result)){
                return BsResult.error(ResultCode.INTERNAL_SERVER_ERROR);
            }
            return BsResult.success(result);
        }
        return BsResult.error(ResultCode.RESOURCE_NOT_FOUND);
    }

    /**
     * xhs编辑器 笔记AI违禁词检测
     * @return
     */
    @PostMapping("/ai/checkText")
    @ApiOperation(value = "xhs编辑器 笔记AI违禁词检测", notes = "xhs编辑器 笔记AI违禁词检测")
    @ResponseBody
    public BsResult aiCheckText(@RequestBody XhsEditorAwemeDTO awemeDTO) {
        if(awemeDTO==null){
            return BsResult.error(ResultCode.PARAM_MISS);
        }
        if(StringUtils.isBlank(awemeDTO.getId())){
            return BsResult.error(ResultCode.RESOURCE_NOT_VALID);
        }
        String eAwemeId=awemeDTO.getId();
        TblUser user = getUser();
        if (user == null || 0L == user.getId()) {
            return BsResult.error(ResultCode.UN_LOGINED);
        }
        Integer userPrivilegeTimes = xhsBusinessManager.getUserPrivilegeTimes(user.getId(), UserPrivilegeEnum.AI_CHECKTEXT);
        if (null == userPrivilegeTimes) {
            //说明这是免费用户
            return BsResult.error(ResultCode.FREE_LIMITED.getCode(),"没有检测字数，请开通会员");
        } else if (userPrivilegeTimes <= 0) {
            return BsResult.error(ResultCode.FREE_LIMITED.getCode(),"检测字数已用完，请升级会员");
        }
        TblXhsEditorAwemeRecord result=editorAwemeRecordService.getById(eAwemeId);
        if(result==null||RowFlagEnum.Deleted.getCode()==result.getFlag()){
            return BsResult.error(ResultCode.RESOURCE_NOT_VALID);
        }
        if (!result.getUserId().equals(user.getId())) {
            return BsResult.error(ResultCode.REQ_REJECT);
        }
        if(ModerationStatusEnum.Disable.getCode()==result.getStatus()){
            return BsResult.error(ResultCode.REQ_REJECT.getCode(),"笔记已被封禁");
        }

        String iText="";
        if(StringUtils.isNotBlank(result.getTitle())){
            try {
                iText+=AESUtil.decrypt(result.getTitle());
            }catch (Exception e){
                return BsResult.error(ResultCode.RESOURCE_NOT_VALID);
            }
        }
        if(StringUtils.isNotBlank(result.getContent())){
            String content=null;
            try {
                content=AESUtil.decrypt((result.getContent()));
            }catch (Exception e){
                return BsResult.error(ResultCode.RESOURCE_NOT_VALID);
            }
            iText+="\n"+content;
        }
        //通常，GLM系列模型词表 token 和汉字换算比例约为 1:1.6
        if (userPrivilegeTimes <= (iText.length()/ 1.6f)) {
            return BsResult.error(ResultCode.FREE_LIMITED.getCode(),"检测字数不够，请升级会员");
        }
        String chatsResponse="";
        if(StringUtils.isNotBlank(iText)){
            ChatCompletionsResponse chatCompletionsResponse =aiChatCompletionsService.getCheckTextByAnalyzeContent(iText);
            if(chatCompletionsResponse!=null){
                chatsResponse=chatCompletionsResponse.getChoices().get(0).getMessage().getContent();
                //扣减提问消耗的字数，提问预设大概需要消耗 200个字，所以这边需要将消耗的字数减去200 ，如果 提问预设修改，需要修改相应的
                Long usageTimes=chatCompletionsResponse.getUsage().getPromptTokens();
                if(usageTimes==null){
                    usageTimes=1L;
                }else if(usageTimes<=206){
                    usageTimes=1L;
                }else{
                    usageTimes-=206;
                }
                xhsBusinessManager.reduceTime(user.getId(), UserPrivilegeEnum.AI_CHECKTEXT,usageTimes);
            }else{
                return BsResult.error(ResultCode.TRY_AGAIN);
            }

        }

        return BsResult.success(chatsResponse);
    }


    @GetMapping("/template/title/tabs")
    @ApiOperation(value = "xhs编辑器-模版-标题模版-标签接口", notes = "xhs编辑器-模版-标题模版-标签接口")
    @ResponseBody
    public BsResult templateTitleTabs(@RequestParam(required = false) Integer  parentId) {
        Long userId = getUserId();
        if (userId == null || 0L == userId) {
            return BsResult.error(ResultCode.UN_LOGINED);
        }
        List<TblXhsEditorTemplateTags> xhsUserTags=null;
        if(parentId==null){
            xhsUserTags=editorTemplateTagsService.queryBytagType(0);
        }else{
            xhsUserTags=editorTemplateTagsService.queryByParentId(parentId);
        }
        List<EditorTemplateTabsVO>  resp=BeanUtil.copyToList(xhsUserTags,EditorTemplateTabsVO.class);
        return BsResult.success(resp);
    }

    @PostMapping("/template/title")
    @ApiOperation(value = "xhs编辑器-模版-标题模版接口", notes = "xhs编辑器-模版-标题模版-接口")
    @ResponseBody
    public BsResult templateTitle(@RequestBody List<String> tags) {
        Long userId = getUserId();
        if (userId == null || 0L == userId) {
            return BsResult.error(ResultCode.UN_LOGINED);
        }
        List<TblXhsEditorTemplateTitle> templateTitleList=editorTemplateTitleService.queryByTags(tags);
        List<EditorTemplateTitleVO>  resp=BeanUtil.copyToList(templateTitleList,EditorTemplateTitleVO.class);
        return BsResult.success(resp);
    }
}
